if (!window.console) window.console ={};
if (!window.console.log) window.console.log = function(){};

function consoleDebug(msg) {}

function ChatGetSetting(key) {}

function ChatSetSetting(key, val) {}

//pub/sub 发布订阅模式 pub sub 绑定在同一信道，pub会触发sub会自动执行

function __GetCookie(cookiename) {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookiename);
    if (ind == -1 ||cookiename == "") return "";
    var ind1 = theCookie.indexOf(';', ind);
    if (ind1 == -1) ind1 = theCookie.length;
    return unescape(theCookie.substring(ind + cookiename.length +1, ind1));
}
function __SetCookie(name, value){
    var Days = 6;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days *3 *60 * 60 * 1000);
    document.cookie = name + "=" +escape(value) + ";expires=" +exp.toGMTString() + ";path=/; domin=localhost";
}

/*var Chat = {};
jQuery.extend(Chat, PubSub);
*/
var reconnectCount = 0,
    resetConnection = false,
    sendmsg = {},
    reconnection;
    // chatcol= __GetCookie('chatcolor')!=""?__GetCookie('chatcolor'):'coblue';
    // console.log('color '+chatcol);
function chatRoomClass() {}

chatRoomClass.prototype = {
    chatUserName:'',
    // chatColor:chatcol,
    currentChatRoom:1,
    socket: null,
    JSMode: true,
    Online: 0,
    chatRoomInfo: [],
    status: undefined,
    sentTo: 0,
    sendToUser: undefined,
    soundOn: true,
    CHAT_SERVER: location.host,
    ws: null,
    onconnect: null,
    chatRoomName: [{
        index: 1,
        name: "大厅"
    }, {
        index: 2,
        name: "副厅"
    }]
}


chatRoomClass.prototype.initws = function(){
    if(1){ 
        //jq('#chater').val()==''
        uname = jq('.vwmy a').text();
        console.log('uname'+uname);
        this.chatUserName = uname;
/*        console.log('uname'+this.chatUserName);
        console.log('cookiename'+__GetCookie('username'));*/
        jq('#chater').val(uname);
    }
    this.JSMode = true;
    sel = this;
    if(1) {
        reconnection = true;
        this.socket = io.connect('http://chat.hiyo.in:3000');
        // this.socket = io.connect();
        this.socket.on('disconnect', function(){
            showShell('聊天室已断开正尝试重新连结');
        });
        this.socket.on('connect', function(){
            msg= {};
            showShell("嗨 哟 链接成功",'success');
            msg.name = sel.chatUserName;
            sel.socket.emit('newuser', msg);
        });
        this.socket.on('news', function (data){
            sel.showMessage(data);
            });
        this.socket.on('sys', function (data){
            //audio.play();
/*            if(jq.trim(data.name)!="龍"&&jq.trim(data.name)!="龙"){
                soundManager.play('msg');
            }       */    
            data = data.name +' 加入聊天室';
            showShell(data,'success');
            // sel.sysMessage(data);
        });
        this.socket.on('history', function (history){
            for(var i=0;i<history.length;i++){
                sel.showMessage(history[i]);
            }
        });
        this.socket.on('onlinelist', function(userlist){
            refreshOnline(userlist);
        })
/*        this.socket.on('onclose', function(){

        });
        socket.on('reconnecting', function(){
            showShell('正在重新链接','err');
        })
        socket.on('connect_failed', function(reason){
            showShell('无法连接服务器, 错误信息'+reason,'err');
        });
        socket.on('disconnect', function(){
            showShell('连接已断开...','err');
        });
        socket.on('reconnect', function(){
              //clearMsg();
              showShell('链接成功,正在初始化...','success');
        });  
        socket.on('reconnect_failed', function(){
          showShell('重新登陆失败...','err');
        });*/     
    }
}
//如果是卡着自己
chatRoomClass.prototype.clearMsg = function(msg){
    putval = msg.to?("@"+msg.to):"";
    jq("#messageform").val(putval);
    // delete msg.to;
    // msg.to='';
}
chatRoomClass.prototype.changeChatRoom = function(chatRoomId) {
    if (this.JSMode) {
        if (this.currentChatRoom != chatRoomId) {
            this.currentChatRoom = chatRoomId;
            this.initws();
        }
    }
}
chatRoomClass.prototype.serverController = function() {

}
chatRoomClass.prototype.showMessage = function(msg) {
    if (msg.col==undefined){msg.col='coblue'};
    if (!msg.to) {
        var uname = (msg.fwrom=='hiyo')?'<span class=\"label-info pull-left\">外场-'+msg.name+ ": </span>":'<span class=\"pull-left chatsend\">'+msg.name+'</span>';
        var umsg = "<div class=\" wellmsg\">";
        umsg +=  uname+ "<span class=\"pull-right stime\">  "+msg.time+"</span>"+"<div class='message'>"+ msg.msg +"</div>" + "</div>";
         var node = jq(umsg);
        // node.hide();
        jq("#chatmessage").append(node);
        // node.show();
    } else if(jq.trim(msg.to)==jq.trim(this.chatUserName)){
        umsg = "<div class=\" wellmsg sysmsg\"><b class=\"label label-info\">";
        umsg += msg.name + "的私聊 </b>" + msg.msg + "<span class=\"pull-left stime\">"+msg.time+"</span></div>";
        node = jq(umsg);
        node.hide();
        jq("#chatmessage").append(node);
        node.slideDown();
    } else if(jq.trim(msg.name)==jq.trim(this.chatUserName)){
        umsg = "<div class=\" wellmsg sysmsg\"><b class=\"label\">@";
        umsg += msg.to + "</b>" + msg.msg + "<span class=\"pull-left stime\">"+msg.time+"</span></div>";
        node = jq(umsg);
        node.hide();
        jq("#chatmessage").append(node);
        node.slideDown();
    }
    jq("#chatmessage").scrollTop(99999);
    console.log();
}
chatRoomClass.prototype.sysMessage = function(msg,time) {
        var umsg = "<div class=\" well sysmsg\">"+msg+"</div>";
        var node = jq(umsg);
        node.hide();
        jq("#chatmessage").prepend(node);
        node.slideDown();
}
chatRoomClass.prototype.changeUserName = function() {
        return this.chatUserName = jq("#chater").val();
}
chatRoomClass.prototype.chatUserInfo = function() {

}
chatRoomClass.prototype.sendMsg = function(newmsg) {
    if(jq.trim(this.chatUserName)==""){
        jq.growl("昵称可不能为空哦！",6);
        return false;}
    newmsg = this.sendmsgType(newmsg);
    if(jq.trim(newmsg.msg)!=''){this.socket.emit('msg', newmsg);}
}
chatRoomClass.prototype.sendmsgType = function(message){
    sendmsg={};
    if (message.substr(0,1) == '@'){
        var p = message.indexOf(' ');
        if (p > 0) {
            sendmsg.to = message.substr(1,p);
            sendmsg.msg = message.substr( p+1);
            console.log("sendmsg" + sendmsg);
        } else {
            return;
        }
    }else {
        sendmsg.msg = message;
    }
    sendmsg.from = 'hiyo';
    sendmsg.col = this.chatColor;
    sendmsg.name = this.chatUserName;
    console.log('noe name is '+ this.uname);
    this.clearMsg(sendmsg);
    console.log('sendname:'+sendmsg.to+'sendmsg:'+sendmsg.msg);
    return sendmsg;
}
var showShell = function(data, style, time ){
    var showTime = time||8;
    var infobox = jq("</p>").addClass('infobox');
    if(style!==undefined){
        infobox.addClass(style);
    }
    infobox.html(data);
    jq("#showInfo").append(infobox);
    infobox.show("drop", {
        direction: "down",
        distance: 50
    }, 1000).
    delay(1000*showTime).
    fadeOut(1000, function() {
        jq(this).remove();
    });
};
jq(function() {
    if(jq('strong').hasClass('vwmy')){
       jq('#chatstrip').show();
    }
    if(__GetCookie('chatbox') == 'false'){
        // console.log(__GetCookie('chatbox'));
        console.log(__GetCookie('chatbox')+'truebox');
        jq("#togglechat").toggle(function(){
            jq(this).text("》嗨 哟!");
            jq("#chatstrip").animate({right:50});
            // jq(".chunwan").animate({right: 420});
            __SetCookie('chatbox',true);
        },
        function(){
            jq(this).text("《嗨 哟!");
            jq("#chatstrip").animate({right:-255});
            // jq(".chunwan").animate({right: -315});
            __SetCookie('chatbox',false);
        }
        );
    } else {
       // console.log(__GetCookie('chatbox')=='true');
       console.log(__GetCookie('chatbox')+'falsebox'); 
       jq("#chatstrip").animate({right:50});
       jq("#togglechat").text("》嗨 哟!");
       jq("#togglechat").toggle(function(){
           jq(this).text("《嗨 哟!");
           jq("#chatstrip").animate({right:-255});
           // jq(".chunwan").animate({right:-315});
           __SetCookie('chatbox',false);
       },
       function(){
           jq(this).text("》嗨 哟!");
           jq("#chatstrip").animate({right:50});
           // jq(".chunwan").animate({right: 420});
           __SetCookie('chatbox',true);
       }
       ); 
    }

    // jq("#sigchat").click(function(){
    //     alert('hello');
    // });
    var _move = false;
    var _x,_y;

    jq("#chatbtn").mousedown(function(e){
        _move = true;
        _x = e.pageX+parseInt(jq("#chatstrip").css("right"));
        _y = e.pageY+parseInt(jq("#chatstrip").css("bottom"));
        jq("#chatstrip").fadeIn(20,0.6);
        console.log(_x+_y);
    });
      jq(document).mousemove(function(e){
          if(_move){
              var x=_x-e.pageX;//移动时根据鼠标位置计算控件左上角的绝对位置
              var y=_y-e.pageY;
              console.log('epagex'+e.pageX+'epagey'+e.pageY);
              console.log('_x'+_x+'_y'+_y)
              console.log('x'+x+'y'+y);
              jq("#chatstrip").css({bottom:y,right:x});//控件新位置
          }
      }).mouseup(function(){
      _move=false;
      jq("#chatstrip").fadeTo("fast", 1);//松开鼠标后停止移动并恢复成不透明
    });
    jq("#sigchat").toggle(function(){
        if(typeof chatroom == 'undefined'){
            console.log("chatroom is undefined");
            chatroom = new chatRoomClass();
            chatroom.initws();
            chatroom.socket.emit('getHistory');
        }
        jq("#chatstrip").animate({bottom:0});
        // jq(".chunwan").animate({bottom:0});
        jq(this).text("隐藏窗口");
        // jq("").hide();
        // jq(".chunwan").show();
        jq(".gotohiyo,#togglechat").toggle();
    },function(){
        jq("#chatstrip").animate({bottom:-403});
        // jq(".chunwan").animate({bottom:-403});
        jq(this).text("进入聊天室");
        // jq(".chunwan").hide();
        jq(".gotohiyo,#togglechat").toggle();
    }
    );
    var jqcontainer = jq("#sidebar");
    // var as = audiojs.createAll();
    // var audio = as[0];
    // audio.load("sound1.mp3");
    jq.growl = function(body, showtime) {
        // audio.play();
        // soundManager.play('msg'); 
        var showT=showtime?showtime:20;
        var rightmsg = jq("<div />").addClass("rightmsg");
        rightmsg.html(body);
        jqcontainer.prepend(rightmsg);
        rightmsg.show("drop", {
            direction: "down",
            distance: 50
        }, 1000).
        delay(1000*showT).
        hide(1000, function() {
            jq(this).remove();
        });
        return rightmsg;
    };

/*    jq("#chater").change(function() {
        if(jq("#chater").val().length>10){
            jq.growl('昵称过长',6);
            jq("#chater").val("");
            jq("#chater").focus();
            return;
        }
        chatroom.chatUserName = chatroom.changeUserName();
        __SetCookie('username', chatroom.changeUserName());
                console.log(__GetCookie('username'));
    });*/
    jq("#messageform").live("keypress",function(e){
        if (e.keyCode == 13) {
          var newmsg = jq("#messageform").val();
          chatroom.sendMsg(newmsg);
          e.preventDefault();
        }
    });
    jq("#send").click(function(){
        var newmsg = jq("#messageform").val()
        chatroom.sendMsg(newmsg);
    });   
});